<template>
  <el-dialog
    :title="title"
    :visible="dialogFormVisible"
    class="form"
    @close="cancelBtn"
  >
    <el-row align="center">
      <el-form
        :model="form"
        label-width="120px"
        label-position="right"
        :rules="rules"
        ref="addForm"
      >
        <el-form-item label="部门名称" prop="name">
          <el-input v-model="form.name" style="width: 80%"></el-input>
        </el-form-item>
        <el-form-item label="部门编码" prop="code">
          <el-input v-model="form.code" style="width: 80%"></el-input>
        </el-form-item>
        <el-form-item label="负责人" prop="manager">
          <el-select
            v-model="form.manager"
            placeholder="请选择"
            style="width: 80%"
            @focus="getManager"
          >
            <el-option
              :label="user.username"
              :value="user.username"
              v-for="user in users"
              :key="user.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="部门介绍" prop="introduce">
          <el-input
            type="textarea"
            v-model="form.introduce"
            :rows="3"
            style="width: 80%"
          ></el-input>
        </el-form-item>
        <el-row type="flex" justify="center">
          <el-button type="primary" size="small" @click="btnOk">确定</el-button>
          <el-button size="small" @click="cancelBtn">取消</el-button>
        </el-row>
      </el-form>
    </el-row>
  </el-dialog>
</template>

<script>
import { getEmployeeSimple } from "@/api/employees";
import {
  getDepartments,
  addDepartments,
  editDepartments,
  updateDepartments,
} from "@/api/departments";
export default {
  name: "addDepart",
  data() {
    // 自定义校验函数
    const checkNameRepeat = async (rule, value, callback) => {
      const { depts } = await getDepartments();
    //   console.log("check", depts);
        // console.log("check",this.form);
      let isRepeat;
      //   编辑状态，判断除我之外不能有这名字。
      if (this.form.id) {
        isRepeat = depts
          .filter((item) => item.id != this.form.id && item.pid == this.form.pid)
          .some((item) => item.name == value);
      } else {
        // 新增状态
        if (this.treeNode.id == "") {
          //根部门
          isRepeat = depts
            .filter((item) => item.pid == "")
            .some((item) => item.name == value);
        } else {
          isRepeat = depts
            .filter((item) => item.pid == this.treeNode.id)
            .some((item) => item.name == value);
        }
      }
      // 找到当前节点的子部门，判断新输入的值是否与子部门的值相同。
      isRepeat == true ? callback(new Error("已经有该部门了")) : callback();
    };
    // 同理编码
    const checkCodeRepeat = async (rule, value, callback) => {
      const { depts } = await getDepartments();
      let isRepeat;
      if (this.form.id) {
        isRepeat = depts
          .some((item) => item.code == value&&item.id !==this.form.id);
      } else {
        isRepeat = depts.some((item) => item.code == value);
      }
      isRepeat == true ? callback(new Error("部门编码重复了")) : callback();
    };
    return {
      users: [],
      form: {
        name: "",
        code: "",
        manager: "",
        introduce: "",
      },
      // 定义校验规则
      rules: {
        name: [
          { required: true, message: "部门名称不能为空", trigger: "blur" },
          {
            min: 1,
            max: 50,
            message: "部门名称要求1-50个字符",
            trigger: "blur",
          },
          {
            trigger: "blur",
            validator: checkNameRepeat,
          },
        ],
        code: [
          { required: true, message: "部门编码不能为空", trigger: "blur" },
          {
            min: 1,
            max: 50,
            message: "部门编码要求1-50个字符",
            trigger: "blur",
          },
          {
            trigger: "blur",
            validator: checkCodeRepeat,
          },
        ],
        manager: [
          { required: true, message: "部门负责人不能为空", trigger: "blur" },
        ],
        introduce: [
          { required: true, message: "部门介绍不能为空", trigger: "blur" },
          {
            trigger: "blur",
            min: 1,
            max: 300,
            message: "部门介绍要求1-50个字符",
          },
        ],
      },
    };
  },
  props: ["dialogFormVisible", "treeNode"],
  methods: {
    async getManager() {
      const result = await getEmployeeSimple();
    //   console.log(result);
      this.users = result;
    },
    btnOk() {
      this.$refs.addForm.validate(async (valid) => {
        if (valid) {
          // 收集到的数据
          // console.log(this.form);
          let result;
          //   有id则为编辑，否则为新增。
          try {
            if (this.form.id) {
              result = await updateDepartments(this.form);
            } else {
              result = await addDepartments({
                ...this.form,
                pid: this.treeNode.id,
              });
            }
            console.log(result);
            this.$emit("update:dialogFormVisible", false);
            this.$emit("getDepart");
          } catch (error) {
            console.log(error.message);
          }
        }
      });
    },
    cancelBtn() {

      this.form = {};
       this.$emit("update:dialogFormVisible", false);
       // 清除之前的校验  可以重置数据 只能重置 定义在data中的数据
      this.$refs.addForm.resetFields(); 

    },
    async editDepart(id) {
      const result = await editDepartments(id);
      console.log("22", result);
      this.form = result;
      console.log(result);
    },
  },
  computed: {
    title() {
      return this.form.id ? "编辑部门" : "新增部门";
    },
  },
};
</script>

<style lang='scss'>
// 修改element的dialog的头部样式
.el-dialog__header {
  background-image: -webkit-linear-gradient(left, #523dc7, #fff);
  .el-dialog__title {
    color: white;
  }
}
</style>